<template>
  <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
  <div id="eCharts" ref="eCharts" :class="'eCharts ' + className"></div>
</template>
<script>
import * as echarts from 'echarts'
export default {
  props: {
    wh: {
      type: String,
      default: 'width:200px;height:200px',
    },
    className: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => {},
    },
  },
  name: 'eCharts',
  data() {
    return {
      myChart: {},
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    options(newValue, oldValue) {
      // console.log(newValue, oldValue)
      if (newValue.series) {
        this.myChart.setOption(newValue)
      } else if (oldValue.series) {
        this.myChart.setOption(oldValue)
      }
    },
  },
  methods: {
    init() {
      if (typeof this.myChart.dispose == 'function') {
        this.myChart.dispose()
      }
      // 基于准备好的dom，初始化echarts实例
      this.myChart = echarts.init(this.$refs.eCharts)
      // 绘制图表
      this.myChart.setOption(this.options)
      window.addEventListener('resize', () => {
        this.myChart.resize()
      })

      this.myChart.on('click', (params) => {
        this.$emit('echartName', params.name)
      })
    },
  },
}
</script>
<style lang="less">
.eCharts {
  width: 100%;
  height: 100%;
}
</style>
